#coding:utf-8

import cv2
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cm as c
import math

import detector

# 自定义的cv图片显示函数，可以改变窗口大小，无法通过按键继续
def cv_show(title,img, block=True):
    cv2.namedWindow(title, cv2.WINDOW_KEEPRATIO) # WINDOW_KEEPRATIO，WINDOW_FREERATIO
    cv2.imshow(title,img)
    #加入cv2.getWindowProperty()的窗口函数判断，当窗口关闭时返回-1，结束循环，使得程序可以自动结束
    while block:
        if cv2.getWindowProperty(title, cv2.WND_PROP_VISIBLE) == 0:
            break
        cv2.waitKey(1)

def display_imgs(imgs, titles=None, num_cols=5, main_title=None):
    num=len(imgs)
    num_rows=math.ceil(num/num_cols)
    fig=plt.figure(figsize=(num_cols*5,num_rows*5))
    fig.suptitle(main_title, font=detector.get_font_yahei(30))
    for i in range(num):
        ax=fig.add_subplot(num_rows,num_cols,i+1)
        ax.imshow(imgs[i],cmap ='gray')
        ax.set_title(titles[i])
# ————————————————
# 原文链接：https://blog.csdn.net/Wslsdx/article/details/110728050  
# https://blog.csdn.net/ITBigGod/article/details/87009082  
        
def display_hists(hists, titles=None, num_cols=5, main_title=None):
    num=len(hists)
    num_rows=math.ceil(num/num_cols)
    fig=plt.figure(figsize=(num_cols*5,num_rows*5))
    fig.suptitle(main_title, font=detector.get_font_yahei(30))
    for i in range(num):
        ax=fig.add_subplot(num_rows,num_cols,i+1)
        ax.plot(hists[i])
        ax.set_title(titles[i])
    
def cv_read(img_file,gray=True):
    if gray == True:
        return cv2.imdecode(np.fromfile(img_file,dtype=np.uint8),0)
    else:
        return cv2.imdecode(np.fromfile(img_file,dtype=np.uint8),-1)

def AdaptiveEquHisto(img):
    adaptive = cv2.createCLAHE(clipLimit=32.0, tileGridSize=(8,8))
    return adaptive.apply(img)


if __name__ == "__main__":
    # 开启交互式作图模式，不同的图会叠加在一张图上，且不会阻塞程序运行
    plt.ion()

    img = cv_read("../fabric-defect/受损+紧经/T03869_00.bmp")
    # cv_show('image_raw', img)

    # 计算直方图时，下面两个函数都可以
    hist = cv2.calcHist([img],[0],None,[256],[0,256])  ## 计算出的是密度曲线
    plt.hist(img.ravel(),256)
    # plt.show(block=False)
    plt.show()

    equ = cv2.equalizeHist(img)
    plt.hist(equ.ravel(),256)
    # plt.show(block=False)
    plt.show()

    # cv_show('image equ histo', equ)

    # 多个自适应均衡化比较：
    adaptive = cv2.createCLAHE(clipLimit=32.0, tileGridSize=(6,12))  # 将图分成几乘几
    adaptive_6x12 = adaptive.apply(img)
    adaptive = cv2.createCLAHE(clipLimit=32.0, tileGridSize=(12,6))
    adaptive_12x6 = adaptive.apply(img)
    adaptive = cv2.createCLAHE(clipLimit=64.0, tileGridSize=(24,24))
    adaptive_24x24 = adaptive.apply(img)


    plt.hist(adaptive_24x24.ravel(),256)
    plt.show()

    # 拼接3张图片
    show = np.hstack((img,equ,adaptive_24x24))
    cv_show('three img',show)

    cv2.destroyAllWindows()